<script lang="ts" setup>
import { ref, onMounted, onUnmounted, h } from 'vue';
import { ElCard, ElSkeleton, ElStatistic, ElCol, ElRow, ElTag, ElTooltip, ElDivider } from 'element-plus';
import { getExceptionStatsApi, type LogApi } from '#/api/core/log';
import { severityMap } from '../data';
import { $t } from '#/locales';
import { formatDateTime } from '@vben/utils';

const loading = ref(false);
const stats = ref<any[]>([]);
const totals = ref({
  total: 0,
  severity0: 0,
  severity1: 0,
  severity2: 0,
});

// 加载统计数据
const loadStats = async () => {
  loading.value = true;
  try {
    const response = await getExceptionStatsApi();
    stats.value = response;

    // 计算总计数据
    totals.value = {
      total: 0,
      severity0: 0,
      severity1: 0,
      severity2: 0,
    };

    response.forEach((item: any) => {
      totals.value.severity0 += item.severity0Count || 0;
      totals.value.severity1 += item.severity1Count || 0;
      totals.value.severity2 += item.severity2Count || 0;
    });

    totals.value.total =
      totals.value.severity0 +
      totals.value.severity1 +
      totals.value.severity2;
  } catch (error) {
    console.error('加载异常统计数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 初始化
onMounted(() => {
  loadStats();
});

// 定时刷新
const refreshInterval = 5 * 60 * 1000; // 5分钟
let timer: number;

onMounted(() => {
  loadStats();
  timer = window.setInterval(loadStats, refreshInterval);
});

onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});

// 格式化短日期（只保留月和日）
const formatShortDate = (dateStr: string) => {
  if (!dateStr) return '';
  try {
    const date = new Date(dateStr);
    return `${date.getMonth() + 1}/${date.getDate()}`;
  } catch (e) {
    return dateStr;
  }
};

// 获取严重级别短标签
const getSeverityShortLabel = (severity: number) => {
  const labels = {
    0: '警告',
    1: '错误',
    2: '严重'
  };
  return labels[severity as keyof typeof labels] || '未知';
};

// 获取严重级别颜色
const getSeverityColor = (severity: number) => {
  const colors = {
    0: '#E6A23C', // 警告：橙色
    1: '#F56C6C', // 错误：红色
    2: '#8B0000'  // 严重：深红色
  };
  return colors[severity as keyof typeof colors] || '#909399';
};
</script>

<template>
  <ElCard
    :title="$t('system.exceptionLog.stats')"
    class="mb-4 exception-stats-card"
    :body-style="{ padding: '8px' }"
  >
    <template #extra>
      <span class="text-xs text-gray-500">{{ loading ? '加载中...' : '更新于：' + formatDateTime(new Date().toISOString()) }}</span>
    </template>

    <ElSkeleton :loading="loading" animated :rows="3" v-if="loading">
    </ElSkeleton>

    <div v-else>
      <ElRow :gutter="16">
        <!-- 左侧：统计摘要 -->
        <ElCol :span="8" class="left-stats">
          <!-- 总计统计信息 -->
          <div class="summary-box">
            <ElStatistic :value="totals.total" title="异常总数" />
            <div class="severity-chart">
              <div v-for="(sev, index) in Object.keys(severityMap)" :key="index"
                   class="severity-bar"
                   :style="{
                     width: `${Math.max(5, (totals[`severity${sev}` as keyof typeof totals] / (totals.total || 1)) * 100)}%`,
                     backgroundColor: getSeverityColor(Number(sev))
                   }"
                   :title="`${severityMap[Number(sev) as keyof typeof severityMap].label}: ${totals[`severity${sev}` as keyof typeof totals]}`">
              </div>
            </div>
          </div>

          <div class="severity-grid">
            <div v-for="(sev, index) in Object.keys(severityMap)" :key="index" class="severity-item">
              <ElTag :type="severityMap[Number(sev) as keyof typeof severityMap].type" size="small">
                {{ severityMap[Number(sev) as keyof typeof severityMap].label }}
              </ElTag>
              <div class="severity-count">{{ totals[`severity${sev}` as keyof typeof totals] }}</div>
            </div>
          </div>
        </ElCol>

        <!-- 右侧：7天数据 -->
        <ElCol :span="16" class="right-stats">
          <div class="stats-table">
            <div class="stats-header">
              <div class="stats-cell date-cell">日期</div>
              <div v-for="(sev, index) in Object.keys(severityMap)" :key="index" class="stats-cell">
                {{ getSeverityShortLabel(Number(sev)) }}
              </div>
              <div class="stats-cell">总计</div>
            </div>

            <div class="stats-body">
              <div v-for="(item, index) in stats.slice(0, 7)" :key="index" class="stats-row">
                <div class="stats-cell date-cell">{{ formatShortDate(item.date) }}</div>
                <div class="stats-cell" :class="{'has-value': item.severity0Count > 0}">{{ item.severity0Count || 0 }}</div>
                <div class="stats-cell" :class="{'has-value': item.severity1Count > 0}">{{ item.severity1Count || 0 }}</div>
                <div class="stats-cell" :class="{'has-value': item.severity2Count > 0}">{{ item.severity2Count || 0 }}</div>
                <div class="stats-cell total-cell">
                  {{ (item.severity0Count || 0) + (item.severity1Count || 0) +
                     (item.severity2Count || 0) }}
                </div>
              </div>
            </div>
          </div>
        </ElCol>
      </ElRow>
    </div>
  </ElCard>
</template>

<style lang="scss" scoped>
.exception-stats-card {
  :deep(.el-card__header) {
    padding: 8px 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 40px;
  }
}

.left-stats {
  padding: 8px;
  display: flex;
  flex-direction: column;
  gap: 12px;

  .summary-box {
    margin-bottom: 4px;
  }

  .severity-chart {
    height: 8px;
    width: 100%;
    display: flex;
    margin-top: 8px;
    border-radius: 4px;
    overflow: hidden;
  }

  .severity-bar {
    height: 100%;
    transition: width 0.3s ease;
  }
}

.severity-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;

  .severity-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 4px 8px;
    background-color: var(--el-fill-color-light);
    border-radius: 4px;

    .severity-count {
      font-weight: bold;
      margin-left: 4px;
    }
  }
}

.right-stats {
  padding: 8px;
}

.stats-table {
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .stats-header {
    display: grid;
    grid-template-columns: 0.8fr repeat(3, 0.6fr) 0.8fr;
    background-color: var(--el-fill-color-light);
    border-bottom: 1px solid var(--el-border-color-lighter);
    font-weight: bold;
    font-size: 13px;
    width: 100%;
    box-sizing: border-box;
    flex-shrink: 0;
  }

  .stats-body {
    max-height: 170px;
    overflow-y: auto;
    width: 100%;
    box-sizing: border-box;

    // 创建滚动条宽度的补偿空间
    padding-right: 0;
    margin-right: 0;

    // 自定义滚动条样式
    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: var(--el-border-color);
      border-radius: 3px;
    }
  }

  .stats-row {
    display: grid;
    grid-template-columns: 0.8fr repeat(3, 0.6fr) 0.8fr;
    border-bottom: 1px solid var(--el-border-color-lighter);
    width: 100%;

    &:last-child {
      border-bottom: none;
    }

    &:hover {
      background-color: var(--el-fill-color);
    }
  }

  .stats-cell {
    padding: 6px 8px;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 13px;
    min-height: 36px;
    box-sizing: border-box;
    overflow: hidden;

    &.date-cell {
      justify-content: flex-start;
    }

    &.total-cell {
      font-weight: bold;
    }

    &.has-value {
      color: var(--el-color-danger);
      font-weight: bold;
    }

    &:not(:last-child) {
      border-right: 1px solid var(--el-border-color-lighter);
    }
  }
}
</style>
